// chrome.extentsion api
const caishui = {
  ports: [],
  /**
   * 发送信息事件
   * @param {String} event  事件名称
   * @param {*} data 事件数据
   * @param {Function} callback 事件回调
   */
  sendMessage(event, data, callback) {
    chrome.runtime.sendMessage(
      {
        event: event,
        data: data
      },
      function(response) {
        callback && callback(response);
      }
    );
  },
  /**
   * 接受发送信息事件
   * @param {String} event  事件名称
   * @param {Function} callback 事件回调
   */
  onMessage(event, callback) {
    chrome.runtime.onMessage.addListener(function(
      request,
      sender,
      sendResponse
    ) {
      let res;
      if (request.event === event) {
        res = callback
          && callback({
            request,
            sender,
            sendResponse
          });
      }
      return res === true;
    });
  },
  /**
   * 本地存储
   * @param {Object} data  存储对象
   * @param {Function} callback 事件回调
   */
  setLocal(data, callback) {
    chrome.storage.local.set(data, function(e) {
      callback && callback(e);
    });
  },
  /**
   * 根据id清除通知信息
   * @param {*} notificationId
   * @param {*} interval
   */
  clearNotifications(notificationId, interval) {
    setTimeout(() => {
      chrome.notifications.clear(notificationId, function(isCleared) {
        if (isCleared) {
          console.log('清除成功');
        }
      });
    }, interval);
  },
  async getLocal(key = null) {
    return new Promise((resolve, reject) => {
      chrome.storage.local.get(key, data => {
        if (typeof key === 'string') {
          resolve(data[key]);
        } else {
          resolve(data);
        }
      });
    });
  },
  /**
   * 系统提示
   * @param message 信息
   * @param interval 消失间隔
   */
  notifications(message, interval = 2000) {
    chrome.notifications.create(
      {
        type: 'basic',
        iconUrl: '../img/icon128.png',
        title: '系统提示',
        message: message
      },
      notificationId => {
        this.clearNotifications(notificationId, interval);
      }
    );
  },
  /**
   * 获取当前页面的tabID
   * @param {Function} callback
   * @param {Object} options
   */
  getCurrentTabId(
    callback,
    options = { active: true, currentWindow: true, lastFocusedWindow: true }
  ) {
    chrome.tabs.query(options, function(tabs) {
      if (callback) {
        if (tabs.length) callback(tabs[0].id);
        else {
          chrome.tabs.query({ active: true }, function(tab) {
            if (tab.length) callback(tab[0].id);
          });
        }
      }
    });
  },
  /**
   * 创建长链接通信
   * @param {String, Number} tid
   * @param {Object} options
   */
  tabsConnect(tid, options) {
    // console.log(this.ports);
    let port = this.ports.find(item => {
      return item.name === options.name && item.tid === tid;
    });
    if (port) return port;
    port = chrome.tabs.connect(tid, options);
    port.tid = tid;
    this.ports.push(port);
    port.onDisconnect.addListener(data => {
      this.ports = this.ports.filter(item => {
        let isCleared = item.name !== data.name || item.tid !== data.tid;
        if (!isCleared) {
          // console.log(item);
          item.disconnect();
          item = null;
        }
        return isCleared;
      });
    });
    return port;
  }
};
export { caishui };
